package com.lanswon.qzsmk.util.pdfutil;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.Logger;

import com.lanswon.qzsmk.exception.SystemException;

public class PDF2Image {
	 private final static Logger logger = (Logger) LoggerFactory.getLogger(PDF2Image.class);
	 public String PDF2Images(String path,String fileName){ 
		 
		 	logger.info("PDF2Images########start()");
		 	//目标图片的路径：
		 	String imagePath = "D:\\template\\";
		 	//目标图片的名称
		    String imageName = fileName.substring(0,fileName.lastIndexOf(".pdf"))+".png";
		 	if(logger.isDebugEnabled()){
		 		logger.debug("imageName:"+imageName);
		 	}
	        File file = new File(path+fileName);  
	        try {  
	            PDDocument doc = PDDocument.load(file);  
	            PDFRenderer renderer = new PDFRenderer(doc);  
	            int pageCount = doc.getNumberOfPages();  
	            for (int i = 0; i < pageCount; i++) {  
	                // 方式1,第二个参数是设置缩放比(即像素)  
	                BufferedImage image = renderer.renderImageWithDPI(i, 296);  
	                // 方式2,第二个参数是设置缩放比(即像素)  
	                // BufferedImage image = renderer.renderImage(i, 2.5f);  
	                ImageIO.write(image, "PNG", new File(imagePath+imageName));  
	            }  
	            
	        } catch (IOException e) {  
	        	e.printStackTrace();
	        	String msg1="IO流异常";
				logger.error(msg1);
				throw new SystemException(SystemException.IOException, msg1);
 
	        }  
	        logger.info("PDF2Images########end()");
	        return imagePath+imageName;
	    }  

}
